let { request, connection } = require("../db/mysql.js");
let { createToken, verifyToken } = require("../utils/token.js")
let md5 = require("md5"); //密码加密
let moment = require("moment") //格式化时间
let svgCaptcha = require('svg-captcha'); //图片验证码

// 用户列表控制器
exports.UserList = async(req, res) => {

    let page = req.query.page || 1;
    let size = req.query.size || 10;
    let level = req.query.level || 0
    let userSql = null;
    let countSql = null;
    if (level == 0) {
        userSql = `SELECT * FROM hg_users WHERE is_show=1 ORDER BY id ASC LIMIT ${(page - 1) * size},${size}`
        countSql = `SELECT COUNT(*) FROM hg_users WHERE is_show=1`
    } else {
        userSql = `SELECT * FROM hg_users WHERE is_show=1 and level=${level} ORDER BY id ASC LIMIT ${(page - 1) * size},${size}`
        countSql = `SELECT COUNT(*) FROM hg_users WHERE is_show=1 and level=${level}`
    }

    let result = await request(userSql)
    let resultCount = await request(countSql)
    console.log(resultCount[0]['COUNT(*)']);
    let count = resultCount[0]['COUNT(*)']
    let pages = Math.ceil(count / size)

    res.json({
        status: 200,
        msg: "成功",
        page: Number(page),
        size: Number(size),
        pages: pages,
        count: count,
        data: result
    });
};
// 删除用户
exports.UserDele = async(req, res) => {
    // req.query   {id:""}
    let deleData = req.query
    let deleSql = `DELETE FROM hg_users WHERE id=${deleData.id}`
    let result = await request(deleSql)
    res.json({
        status: 200,
        msg: "删除成功",
        data: result
    })
};
// 添加用户控制器
exports.UserAdd = (req, res) => {
    // 注册规则
    // 先判断用户名是否存在
    // 如果存在：提示该用户已经存在，请登录
    // 如果不存在：可以注册该用户
    console.log(req.body);
    //    {
    //         username: '小好',
    //         password: '123456',
    //         level: '5',
    //         is_show: '1'
    //       }

    let {
        username,
        phone,
        email,
        age,
        sex,
        level,
        address,
        imgsrc,
    } = req.body
        // 处理其他
    let password = md5(req.body.password);
    // 设定默认值
    let is_show = '1';
    let is_username = `SELECT * FROM hg_users WHERE username="${username}"`
    connection.query(is_username, (err, data) => {
        if (err) {
            return res.json({
                status: 1001,
                msg: "查询失败"
            })
        } else {
            console.log(data);
            if (data.length > 0) {
                // 条件成立说明用户名已存在
                return res.json({
                    status: 1002,
                    msg: "用户已经存在，请登录"
                })
            } else {
                //说明用户名可以注册
                let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
                let id = +new Date();
                // 添加数据
                let addSql = `insert into hg_users SET id ="${id}",username="${username}",password="${password}",phone="${phone}", email="${email}",imgsrc="${imgsrc}", age="${age}", sex="${sex}",level="${level}",address="${address}",is_show="${is_show}",create_time="${nowTime}"`
                console.log(addSql);
                connection.query(addSql, (err, result) => {
                    if (err) {
                        return res.json({
                            status: 1003,
                            msg: "添加失败"
                        })
                    } else {
                        return res.json({
                            status: 200,
                            msg: "添加成功",
                            data: result
                        })
                    }
                })
            }

        }
    })

};
// 修改用户
exports.UserEdit = async(req, res) => {
    console.log(req.body); // {age:"",email:"",address:"",id:"",is_show:""}
    // 只允许修改年龄和邮箱,地址,是否显示
    let editData = req.body
    let editSql = `UPDATE hg_users SET age=${editData.age},email="${editData.email}",address="${editData.address}",is_show="${editData.is_show}" WHERE id=${editData.id}`
    let result = await request(editSql)
    res.json({
        status: 200,
        msg: "修改成功",
        data: result
    })
};
// 图片验证码
exports.Captcha = (req, res) => {
    var captcha = svgCaptcha.create({
        size: 4, // 随机字符串的长度
        ignoreChars: '0o1i', // 忽略相似字符
        noise: 5, // 干扰线的条数
        color: true, // 颜色
        background: '#fff', //背景颜色
    });
    // 图形验证码的标识符
    let client = createToken({
        captchaData: captcha.text,
    });
    // 2、返回给验证码给前端
    let resCaptcha = {
        client: client,
        captcha: captcha.data,
        status: 200,
        msg: "验证码获取成功",

    };
    // res.type('svg')
    res.status(200).send(resCaptcha);
};

// 登录控制器
exports.Login = async(req, res) => {
    let { username, client, captcha } = req.body
    let password = md5(req.body.password)

    if (!client || !captcha) {
        res.json({
            status: 1006,
            msg: "验证码不能为空"
        })
        return;
    };

    var rel = await verifyToken(client);
    if (rel.captchaData.toLowerCase() !== captcha.toLowerCase()) {
        res.json({
            status: 1003,
            msg: "验证码不正确"
        })
        return;
    };

    // 判断用户名是否存在
    let is_username = `SELECT * FROM hg_users WHERE username="${username}"`
    connection.query(is_username, (err, data) => {
        if (err) {
            return res.json({
                status: 1001,
                msg: "查询失败"
            })
        } else {
            console.log(data);
            if (data.length > 0) {
                // 条件成立说明用户名已存在
                let sql = `SELECT * FROM hg_users WHERE username="${username}" AND password="${password}"`
                console.log(sql);
                connection.query(sql, (err, result) => {
                    if (err) {
                        return res.json({
                            status: 1004,
                            msg: "查询失败"
                        })
                    } else {
                        console.log(result);
                        if (result.length > 0) {
                            let token = createToken({
                                isLogin: true,
                                username: username
                            })
                            return res.json({
                                status: 200,
                                token: token,
                                msg: "登录成功"
                            })
                        } else {
                            return res.json({
                                status: 1005,
                                msg: "用户名或者密码错误"
                            })
                        }
                    }
                })
            } else {
                return res.json({
                    status: 1002,
                    msg: "用户不存在，请注册"
                })
            }

        }
    })

};